import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/request'
import { isURL } from '@/utils/validate'
import productRoutes from './product' //写死的路由
import _ from 'lodash'

Vue.use(Router)

//重写push方法，解决相同路径跳转报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 页面路由(独立页面)
export const pageRoutes = [
  {
    path: '/404',
    component: () => import('@/views/pages/404'),
    name: '404',
    meta: { title: '404未找到' },
    beforeEnter (to, from, next) {
      // 拦截处理特殊业务场景
      // 如果, 重定向路由包含__双下划线, 为临时添加路由
      if (/__.*/.test(to.redirectedFrom)) {
        return next(to.redirectedFrom.replace(/__.*/, ''))
      }
      next()
    }
  } ,
  { path: '/login', component: () => import('@/views/pages/login'), name: 'login', meta: { title: '登录' } }
]

// 模块路由(基于主入口布局页面)
export const moduleRoutes = {
  path: '/',
  component: () => import('@/views/main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口布局' },
  children: [
    { path: '/home', component: () => import('@/views/modules/home'), name: 'home', meta: { title: '首页', isTab: false } },
    ...productRoutes
  ]
}

//跳转路由或者添加动态路由
export function addDynamicRoute (routeParams, router) {
  // 组装路由名称, 并判断是否已添加, 如是: 则直接跳转
  var routeName = routeParams.routeName
  var dynamicRoute = window.SITE_CONFIG['dynamicRoutes'].filter(item => item.name === routeName)[0]
  if (dynamicRoute) {
    return router.push({ name: routeName, params: routeParams.params })
  }
  // 否则: 添加并全局变量保存, 再跳转
  dynamicRoute = {
    path: routeName,
    component: () => import(`@/views/modules/${routeParams.path}`),
    name: routeName,
    meta: {
      ...window.SITE_CONFIG['contentTabDefault'],
      menuId: routeParams.menuId,
      title: `${routeParams.title}`
    }
  }
  router.addRoutes([
    {
      ...moduleRoutes,
      name: `main-dynamic__${dynamicRoute.name}`,
      children: [dynamicRoute]
    }
  ])
  window.SITE_CONFIG['dynamicRoutes'].push(dynamicRoute)
  router.push({ name: dynamicRoute.name, params: routeParams.params })
}

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  routes: pageRoutes.concat(moduleRoutes)
})

router.beforeEach((to, from, next) => {
  let data  = {
    "code": 0,
    "msg": "success",
    "data": [ {
      "id": "1067246875800000401",
      "pid": "0",
      "children": [{
        "id": "1067246875800000402",
        "pid": "1067246875800000401",
        "children": [],
        "name": "通知管理",
        "url": "sys/notice",
        "params": [],
        "type": 0,
        "icon": "icon-bell",
        "permissions": "",
        "sort": 0,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1067246875800000403",
        "pid": "1067246875800000401",
        "children": [],
        "name": "我的通知",
        "url": "sys/notice-user",
        "params": [],
        "type": 0,
        "icon": "icon-notification",
        "permissions": "sys:notice:all",
        "sort": 1,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }],
      "name": "站内通知",
      "url": "",
      "params": [],
      "type": 0,
      "icon": "icon-bell",
      "permissions": "",
      "sort": 12,
      "createDate": "2020-06-02 19:06:33",
      "resourceList": null,
      "parentName": null
    }, {
      "id": "1067246875800000036",
      "pid": "0",
      "children": [{
        "id": "1067246875800000037",
        "pid": "1067246875800000036",
        "children": [],
        "name": "登录日志",
        "url": "sys/log-login",
        "params": [],
        "type": 0,
        "icon": "icon-filedone",
        "permissions": "",
        "sort": 0,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1067246875800000038",
        "pid": "1067246875800000036",
        "children": [],
        "name": "操作日志",
        "url": "sys/log-operation",
        "params": [],
        "type": 0,
        "icon": "icon-solution",
        "permissions": "",
        "sort": 1,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1067246875800000039",
        "pid": "1067246875800000036",
        "children": [],
        "name": "异常日志",
        "url": "sys/log-error",
        "params": [],
        "type": 0,
        "icon": "icon-file-exception",
        "permissions": "",
        "sort": 2,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }],
      "name": "日志管理",
      "url": "",
      "params": [],
      "type": 0,
      "icon": "icon-container",
      "permissions": "",
      "sort": 17,
      "createDate": "2020-06-02 19:06:33",
      "resourceList": null,
      "parentName": null
    }, {
      "id": "1067246875800000019",
      "pid": "0",
      "children": [{
        "id": "1067246875800000020",
        "pid": "1067246875800000019",
        "children": [],
        "name": "菜单管理",
        "url": "sys/menu",
        "params": [],
        "type": 0,
        "icon": "icon-unorderedlist",
        "permissions": null,
        "sort": 0,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1067246875800000025",
        "pid": "1067246875800000019",
        "children": [],
        "name": "参数管理",
        "url": "sys/params",
        "params": [],
        "type": 0,
        "icon": "icon-fileprotect",
        "permissions": "",
        "sort": 1,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1067246875800000031",
        "pid": "1067246875800000019",
        "children": [],
        "name": "字典管理",
        "url": "sys/dict-type",
        "params": [],
        "type": 0,
        "icon": "icon-gold",
        "permissions": "",
        "sort": 2,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1164489061834969089",
        "pid": "1067246875800000019",
        "children": [],
        "name": "行政区域",
        "url": "sys/region",
        "params": [],
        "type": 0,
        "icon": "icon-location",
        "permissions": "0",
        "sort": 3,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1067246875800000047",
        "pid": "1067246875800000019",
        "children": [],
        "name": "定时任务",
        "url": "job/schedule",
        "params": [],
        "type": 0,
        "icon": "icon-edit-square",
        "permissions": "",
        "sort": 3,
        "createDate": "2020-06-02 19:08:07",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1067246875800000060",
        "pid": "1067246875800000019",
        "children": [],
        "name": "文件上传",
        "url": "oss/oss",
        "params": [],
        "type": 0,
        "icon": "icon-upload",
        "permissions": "",
        "sort": 4,
        "createDate": "2020-06-02 19:08:34",
        "resourceList": null,
        "parentName": null
      }],
      "name": "系统设置",
      "url": "",
      "params": [],
      "type": 0,
      "icon": "icon-setting",
      "permissions": null,
      "sort": 18,
      "createDate": "2020-06-02 19:06:33",
      "resourceList": null,
      "parentName": null
    }, {
      "id": "1067246875800000040",
      "pid": "0",
      "children": [ {
        "id": "1067246875800000041",
        "pid": "1067246875800000040",
        "children": [],
        "name": "服务监控",
        "url": "{{ window.SITE_CONFIG[\"apiURL\"] }}/monitor/index.html",
        "params": [],
        "type": 0,
        "icon": "icon-medicinebox",
        "permissions": "",
        "sort": 0,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }, {
        "id": "1067246875800000042",
        "pid": "1067246875800000040",
        "children": [],
        "name": "接口文档",
        "url": "{{ window.SITE_CONFIG[\"apiURL\"] }}/doc.html",
        "params": [],
        "type": 0,
        "icon": "icon-file-word",
        "permissions": "",
        "sort": 1,
        "createDate": "2020-06-02 19:06:33",
        "resourceList": null,
        "parentName": null
      }],
      "name": "系统监控",
      "url": "",
      "params": [],
      "type": 0,
      "icon": "icon-desktop",
      "permissions": "",
      "sort": 20,
      "createDate": "2020-06-02 19:06:33",
      "resourceList": null,
      "parentName": null
    }, ]
  }
  if (window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] || fnCurrentRouteIsPageRoute(to, pageRoutes)) {
    return next()
  }
  window.SITE_CONFIG['menuList'] = data.data
  fnAddDynamicMenuRoutes(window.SITE_CONFIG['menuList'])
  next({ ...to, replace: true })
  /*
  // 添加动态(菜单)路由
  // 已添加或者当前路由为页面路由, 可直接访问
  if (window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] || fnCurrentRouteIsPageRoute(to, pageRoutes)) {
    return next()
  }
  // 获取字典列表, 添加并全局变量保存
  http.get('/sys/dict/type/all').then(({ data: res }) => {
    if (res.code !== 0) {
      return
    }
    window.SITE_CONFIG['dictList'] = res.data
  }).catch(() => {})
  // 获取菜单列表, 添加并全局变量保存
  http.get('/sys/menu/nav').then(({ data: res }) => {
    if (res.code !== 0) {
      Vue.prototype.$message.error(res.msg)
      return next({ name: 'login' })
    }
    window.SITE_CONFIG['menuList'] = res.data
    fnAddDynamicMenuRoutes(window.SITE_CONFIG['menuList'])
    next({ ...to, replace: true })
  }).catch(() => {
    next({ name: 'login' })
  })
  */
})

/**
 * 判断当前路由是否为页面路由
 * @param {*} route 当前路由
 * @param {*} pageRoutes 页面路由
 */
function fnCurrentRouteIsPageRoute (route, pageRoutes = []) {
  var temp = []
  for (var i = 0; i < pageRoutes.length; i++) {
    if (route.path === pageRoutes[i].path) {
      return true
    }
    if (pageRoutes[i].children && pageRoutes[i].children.length >= 1) {
      temp = temp.concat(pageRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteIsPageRoute(route, temp) : false
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    const menu = menuList[i]
    if (menu.children && menu.children.length >= 1) {
      temp = temp.concat(menu.children)
      continue
    }
    // 组装路由
    var route = {
      path: '',
      component: null,
      name: '',
      meta: {
        ...window.SITE_CONFIG['contentTabDefault'],
        menuId: menu.id,
        title: menu.name
      }
    }
    // eslint-disable-next-line
    let URL = (menu.url || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
    
    if (isURL(URL)) {
      route['path'] = route['name'] = `i-${menu.id}`
      route['meta']['iframeURL'] = URL
    } else if (/.*:[a-zA-Z]+/.test(URL)) {
      // 如果最后是 path参数
      const idx = URL.lastIndexOf('/')
      const prefixURL = URL.substring(0, idx).replace(/^\//, '').replace(/_/g, '-')
      const pathParam = URL.substring(idx + 1)
      route['path'] = prefixURL.replace(/\//g, '-') + '/' + pathParam
      if (menu.params) {
        route['name'] = route['path'] + '-' + _.keyBy(menu.params, 'name')[pathParam.substring(1)]['value']
      }
      route['component'] = () => import(`@/views/modules/${prefixURL}`)
    } else {
      URL = URL.replace(/^\//, '').replace(/_/g, '-')
      route['path'] = route['name'] = URL.replace(/\//g, '-')
      route['component'] = () => import(`@/views/modules/${URL}`)
    }

    if (menu.params && menu.params.length > 0) {
      route['meta']['params'] = menu.params
    }
    routes.push(route)
  }
  if (temp.length >= 1) {
    return fnAddDynamicMenuRoutes(temp, routes)
  }
  // 添加路由
  router.addRoutes([
    {
      ...moduleRoutes,
      name: 'main-dynamic-menu',
      children: routes
    },
    { path: '*', redirect: { name: '404' } }
  ])
  console.log(router)
 
  window.SITE_CONFIG['dynamicMenuRoutes'] = routes
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = true
}

export default router
